﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using PerfumeShopManagement.Model;
using PerfumeShopManagement.Utility;

namespace PerfumeShopManagement.DAL
{
    public class DalProduct : DalAbstractBase<Product, int>
    {
        public override Product GetObjectById(int id)
        {
            int productId = id;
            var result = (from p in _context.Products
                          where p.ProductId.Equals(productId)
                          select p).FirstOrDefault();
            return result;
        }

        public override List<Product> GetAllObjects()
        {
            var result = (from p in _context.Products
                          select p);
            if (result != null)
                return result.ToList<Product>();

            return new List<Product>();
        }

        public override List<Product> GetObjectsByCriteria(Product obj)
        {
            Product product = obj;

            var productsQuery = (from p in _context.Products
                                   select p);

            if (product.ProductId != 0)
                productsQuery = productsQuery.Where(p => p.ProductId.Equals(product.ProductId));

            if (!StringUtil.isEmptyOrBlank(product.ProductName))
                productsQuery = productsQuery.Where(p => p.ProductName.Contains(product.ProductName));

            if (productsQuery != null)
                return productsQuery.ToList<Product>();

            return new List<Product>();
        }

        public override bool Insert(Product obj)
        {
            Product product = obj;

            _context.Products.AddObject(product);
            _context.SaveChanges();

            return true;
        }

        public override bool Update(Product obj)
        {
            Product product = obj;

            Product productRow = _context.Products.Single(
                p => p.ProductId == product.ProductId);
            productRow.ProductName = product.ProductName;
            productRow.Price = product.Price;
            productRow.Inventory = product.Inventory;
            productRow.DetailInfo = product.DetailInfo;
            productRow.CategoryId = product.CategoryId;
            _context.SaveChanges();

            return true;
        }

        public override bool DeleteById(int id)
        {
            bool deleted = false;
            int productId = id;
            var result = (from p in _context.Products
                          where p.ProductId.Equals(productId)
                          select p).FirstOrDefault();
            if (result != null)
            {
                _context.Products.DeleteObject((Product)result);
                _context.SaveChanges();
                deleted = true;
            }

            return deleted;
        }
    }
}
